package org.itboys.mobile.service.mysql.front;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.itboys.admin.entity.lasted.SystemDictionary;
import org.itboys.admin.service.lasted.SystemDictionaryService;
import org.itboys.commons.CommonConstants;
import org.itboys.commons.ErrorException;
import org.itboys.commons.utils.http.OkHttpUtil;
import org.itboys.commons.utils.time.TimeUtils;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.dao.order.SundayOrderProductMapper;
import org.itboys.mobile.dao.product.SundayProductMapper;
import org.itboys.mobile.dao.promotion.SundayTeamGroupMemberMapper;
import org.itboys.mobile.dto.SundayMemberDto;
import org.itboys.mobile.dto.count.SundayCountDto;
import org.itboys.mobile.dto.count.SundayCountProductDto;
import org.itboys.mobile.dto.count.SundayCountTotalDto;
import org.itboys.mobile.dto.order.SundayOrderDto;
import org.itboys.mobile.dto.order.SundayOrderProductDto;
import org.itboys.mobile.entity.mongo.SundayAddress;
import org.itboys.mobile.entity.mongo.SundayMember;
import org.itboys.mobile.entity.mysql.order.SundayOrder;
import org.itboys.mobile.entity.mysql.order.SundayOrderProduct;
import org.itboys.mobile.entity.mysql.product.SundayProduct;
import org.itboys.mobile.entity.mysql.promotion.SundayTeamGroup;
import org.itboys.mobile.entity.mysql.promotion.SundayTeamGroupMember;
import org.itboys.mobile.entity.mysql.wallet.SundayWallet;
import org.itboys.mobile.service.mongo.front.*;
import org.itboys.mobile.service.mongo.front.dynamic.SundayFrontDynamicService;
import org.itboys.mobile.util.NumberUtil;
import org.itboys.mysql.service.BaseMySqlService;
import org.itboys.param.ParamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;

/**
 * 作者：jiangxiong
 * 日期：2017年5月8日
 * 联系方式 ：empty90911@126.com
 * 描述：圣代_订单_service_mobile
 */
@Service
public class SundayFrontOrderService extends BaseMySqlService<SundayOrder> {
    @Autowired
    private SundayFrontCountService countService;
    @Autowired
    private SundayFrontMemberService memberService;
    @Autowired
    private SundayFrontAddressService addressService;
    @Autowired
    private SundayFrontCouponService couponService;
    @Autowired
    private SundayFrontWalletService walletService;
    @Autowired
    private SundayOrderProductMapper orderProductMapper;
    @Autowired
    private SundayProductMapper productMapper;
    @Autowired
    private SundayFrontTeamGroupService teamGroupService;
    @Autowired
    private SundayTeamGroupMemberMapper teamGroupMemberMapper;
    @Autowired
    private SundayFrontCommentService commentService;
    @Autowired
    private SundayFrontCartService cartService;
    /*@Autowired
    private SundayFrontCommunityDynamicService communityDynamicService;*/
    @Autowired
    private SundayFrontDynamicService dynamicService;
    @Autowired
    private SystemDictionaryService dictionaryService;
    @Autowired
    private SundayFrontCollectionService collectionService;

    /**
     * 创建订单
     * @param memberId
     * @param cartIds
     * @param isUsedAiGou
     * @param isUsedBalance
     * @param teamIsJoin
     * @param teamGroupId
     * @param remark
     * @param addressId
     * @return
     */
    @Transactional
    public Map<String,Object> createOrder(Long memberId,List<Long> cartIds,
                                          Integer isUsedAiGou,
                                          Integer isUsedBalance,
                                          Integer isUsedConch,
                                          Integer teamIsJoin,
                                          Long teamGroupId,
                                          String idCard,
                                          String realName,
                                          String remark,
                                          Long addressId,
                                          Integer sendType){

        Map<String,Object> result = new HashMap<String,Object>();


        //返回数据
        //String payAmount ="";//本次付款金额
        String orderIds = "";//需要支付的订单
        //Integer isNeedToPay=1;//订单是否需要支付。默认是

       // String orderNo=null;//订单编号
        SundayAddress address = null;//收货地址
        if(!LongUtil.isNotZreo(addressId)){
            throw new ErrorException("请选择一个收货地址");
        }else{
            address = addressService.getById(addressId);
        }
        //2获取购物车数据
        SundayCountTotalDto countTotalDto =countService.countCart( memberId,cartIds,isUsedAiGou, isUsedBalance,isUsedConch, teamIsJoin, teamGroupId,sendType);
       //本次结算的多个订单是否需要支付。
        Integer isNeedToPay=countTotalDto.getPayAmount().compareTo(new BigDecimal("0"))!=1?0:1;
        //用户信息
        SundayMember member = memberService.getById(memberId);
       //0常量
        BigDecimal zero= new BigDecimal("0");
        //根据结算dto中数量生成多个订单
        for(SundayCountDto countDto:countTotalDto.getCounts()){
            //2018年2月1日，判断结算页面是否是由手机物理页面返回的数据
            /*if(!ListUtil.isNotNull(countDto.getProducts())){
                throw new ErrorException("数据已过期，请刷新后重试");
            }*/
            //订单编号
            SundayOrder order = new SundayOrder();
            order.setOrderNo(NumberUtil.generateNumber("AG"));
            order.setType(countDto.getType());
            order.setTotalAmount(countDto.getTotalAmount());
            order.setPayAmount(countDto.getPayAmount());
            order.setSendType(countDto.getSendType());
            //订单状态
            Integer status = SundayCommonConstants.ORDER_STATUS_DFK;
            //判断订单是否需要支付
            if(countDto.getPayAmount().compareTo(new BigDecimal("0"))!=1){
                //是否为拼团订单
                if(countDto.getType()==SundayCommonConstants.type_pintuan){
                    //0单独购买，1参与别人的，2自己开团
                    if(countDto.getTeamIsJoin()==0){
                        status=SundayCommonConstants.ORDER_STATUS_DFH;//待发货
                    }else{
                        status=SundayCommonConstants.ORDER_STATUS_DPT;//待拼团；
                    }
                }else{
                    //2018年2月24日，根据配送方式判断
                    //门店配送为待配送
                    if(countDto.getSendType()==SundayCommonConstants.send_type_send){
                        status=SundayCommonConstants.ORDER_STATUS_DFH;//待发货
                     //自提为配送中
                    }else if(countDto.getSendType()==SundayCommonConstants.send_type_self){
                        status=SundayCommonConstants.ORDER_STATUS_PSZ;//配送中
                    }

                }

            }
            order.setStatus(status);
            //如果是自营订单。扣减爱购币、扣减优惠券、扣减余额。特殊商品类型处理逻辑
            if(countDto.getShopId().longValue()==0l){
                //初始化抵扣变量

                order.setCouponAmount(zero);
                order.setCouponId(0l);
                order.setAiGouUsedCoin(zero);
                order.setAiGouUsedAmount(zero);
                order.setBalanceUsedAmount(zero);
                order.setConchUsedAmount(zero);




                //2018年2月4日对比爱购币兑换
                if(countDto.getType()!=6){

                    //扣减优惠券
                    if(LongUtil.isNotZreo(countDto.getCouponId())){
                        couponService.usedCoupon(countDto.getCouponId(),countDto.getMemberId());
                        order.setCouponAmount(countDto.getCouponAmount());
                        order.setCouponId(countDto.getCouponId());
                    }
                    //扣减爱购币
                    if(countDto.getIsUseAigou()== SundayCommonConstants.YES&&
                            countDto.getAiGouUsedCoin().compareTo(zero)==1){
                        order.setAiGouUsedCoin(countDto.getAiGouUsedCoin());
                        order.setAiGouUsedAmount(countDto.getAiGouUsedAmount());
                        //扣减钱包中的爱购币。
                        walletService.changeWallet(countDto.getMemberId(),SundayCommonConstants.wallet_record_type_coin_shop,countDto.getAiGouUsedCoin(),order.getOrderNo(),"订单扣减爱购币:"+countDto.getAiGouUsedCoin(),null);
                    }
                    //扣减余额
                    if(countDto.getIsUseBalance()==SundayCommonConstants.YES){
                        logger.info("------余额抵扣的金额-----"+countDto.getBalanceUsedAmount());
                        order.setBalanceUsedAmount(countDto.getBalanceUsedAmount());
                        //扣减钱包中的余额
                        walletService.changeWallet(countDto.getMemberId(),SundayCommonConstants.wallet_record_type_amount_shop,countDto.getBalanceUsedAmount(),order.getOrderNo(),"订单扣减余额:"+countDto.getBalanceUsedAmount(),null);
                    }
                    //扣减贝壳。2018年3月5日
                    if(countDto.getIsUseConch()==SundayCommonConstants.YES){
                        logger.info("------贝壳抵扣的金额-----"+countDto.getConchUsedAmount());
                        order.setConchUsedAmount(countDto.getConchUsedAmount());
                        //扣减钱包中的余额
                        walletService.changeWallet(countDto.getMemberId(),SundayCommonConstants.wallet_record_type_conch_shop,countDto.getConchUsedAmount(),order.getOrderNo(),"订单扣减贝壳:"+countDto.getConchAbleAmount(),null);
                    }
                     //根据结算类型判断一些必要的参数
                    //海淘必须上传身份证
                    if(countDto.getType()==SundayCommonConstants.type_haitao){
                       /* if(StringUtils.isEmpty(idCard)||StringUtils.isEmpty(realName)){
                            throw new ErrorException("海淘商品必须填写身份证和真实姓名");
                        }else{
                            //更新用户的身份证和真实姓名
                            member.setIdCard(idCard);
                            member.setRealName(realName);

                            memberService.updateExceptEmpty(memberId,member);

                        }*/
                    }
                    //拼团
                    if(countDto.getType()==SundayCommonConstants.type_pintuan){



                        //拼团组ID
                        order.setTeamGroupId(countDto.getTeamGroupId());
                        //拼团中，拼团人的信息。生成后再写入。
                        //order.setTeamGroupMemberId();
                        //0单独购买，1参与别人的，2自己开团
                        order.setTeamIsJoin(countDto.getTeamIsJoin());
                        //2018年2月1日，每个用户针对每个团，只能参与一次
                        if(countDto.getTeamIsJoin()==SundayCommonConstants.team_type_join&&LongUtil.isNotZreo(countDto.getTeamGroupId())){
                            if(teamGroupService.checkIsJoin(memberId,teamGroupId)){
                                throw new ErrorException("您已经参与过本次拼团。");
                            }
                        }
                    }
                }else{
                    //爱购币兑换
                    if(countDto.getPayAmount().compareTo(countDto.getAiGouTotalCoin())==1){
                        throw new ErrorException("爱购币不足，所需爱购币："+ countDto.getPayAmount());
                    }else {
                        order.setStatus(SundayCommonConstants.ORDER_STATUS_DFH);
                        isNeedToPay=SundayCommonConstants.NO;
                    }

                }
            }
            //组建订单的其他数据
            order.setMemberId(memberId);
            order.setMemberName(member.getNickName());
            order.setMemberIdCard(idCard);
            order.setMemberRealName(realName);
            order.setShopId(countDto.getShopId());
            order.setShopName(countDto.getShopName());
            order.setReceiveName(address.getReceiveName());
            order.setReceiveMobile(address.getReceiveMobile());
            order.setProvinceId(address.getProvinceId());
            order.setProvinceName(address.getProvinceName());
            order.setCityId(address.getCityId());
            order.setCityName(address.getCityName());
            order.setDistrictId(address.getDistrictId());
            order.setDistrictName(address.getDistrictName());
            order.setReceiveAddress(address.getReceiveAddress());
            order.setRemark(remark);
            order.setInfo(countDto.getInfo());
            order.setSendAmount(countDto.getSendAmount());

           // 特殊属性。有一些只能立即购买的商品。如拼团，直接在订单里面保存商品ID
            order.setProductId(countDto.getProducts().get(0).getId());
            //2018年2月2日，保持订单title
            StringBuilder title = new StringBuilder();
            for(SundayCountProductDto countProductDto:countDto.getProducts()){
                title.append(countProductDto.getName()+",");
            }
            order.setTitle(title.toString());
            super.insert(order);

            orderIds+=order.getId()+",";
            //保存订单商品
          //  List<SundayOrderProduct> orderProducts = new ArrayList<SundayOrderProduct>();
            for(SundayCountProductDto countProductDto:countDto.getProducts()){
                SundayOrderProduct orderProduct =
                       /* Long orderId, Long productId, String name, String barCode, String image, Integer num,Integer store,String standard, Integer status,
                        BigDecimal price, Integer type*/
                        new SundayOrderProduct(order.getId(),countProductDto.getId(),
                                countProductDto.getName(), countProductDto.getBarCode(),countProductDto.getImage(),countProductDto.getNum(),
                                countProductDto.getStore(),countProductDto.getStandard(),countProductDto.getStatus(),
                                countProductDto.getPrice(),countProductDto.getType());
                orderProductMapper.insert(orderProduct);
                //orderProducts.add(orderProduct);
                //更新产品销量和库存
                SundayProduct product = new SundayProduct();
                product.setId(countProductDto.getId());
                product.setStore(countProductDto.getStore()-countProductDto.getNum());
                product.setSaleNumber(countProductDto.getSaleNumber()+countProductDto.getNum());
                productMapper.update(product);
            }
            //特殊商品类型，订单生成后处理逻辑。直营商城才会出现
            if(countDto.getShopId().longValue()==0l){
                //不需要支付订单，执行特殊逻辑。直营商城才会出现
                if(countDto.getPayAmount().compareTo(zero)!=1){
                        callback(order);
                }
            }
            //删除购物车
            cartService.deleteCart(cartIds,memberId,null);

        }

            //本次支付返回的信息
            result.put("orderIds",orderIds.substring(0,orderIds.length()-1));
            result.put("isNeedToPay",isNeedToPay);
            result.put("payAmount",countTotalDto.getPayAmount());
            result.put("addressId",address.getId());
            result.put("receiveName",address.getReceiveName());
            result.put("receiveMobile",address.getReceiveMobile());
            result.put("receiveAddress",address.getProvinceName()+address.getCityName()+address.getCityName()+address.getReceiveAddress());
            //result.put("isNeedToPay",isNeedToPay);
            result.put("info","isNeedToPay:本次订单是否需要支付，1是（转入支付页面），0转入（支付成功页面），");
            return result;
    }

    /**
     * 订单支付成功或余额抵扣后回掉。主要是处理拼团订单
     * @param order
     */
    @Transactional
    public void callback(SundayOrder order){
           /* if(1==1){
                return;
            }*/
            if(order.getType()==SundayCommonConstants.type_pintuan){
                //自己开团
                if(order.getTeamIsJoin()==SundayCommonConstants.team_type_start){
                    logger.info("自己开团");
                    teamGroupService.join( order.getMemberId(),order.getProductId(),order.getId(),0l);
                }
                //参与别人的团
                if(order.getTeamIsJoin()==SundayCommonConstants.team_type_join){
                    logger.info("给别人拼团");
                    teamGroupService.join( order.getMemberId(),order.getProductId(),order.getId(),order.getTeamGroupId());
                    //判断团购是否足够发团，修改拼团组信息，修改订单信息
                    SundayTeamGroup teamGroup = teamGroupService.find(order.getTeamGroupId());
                    //已经达到最大人数
                    if(teamGroup.getSurplusNumber()<=0){
                        //1，修改拼团组状态
                        teamGroup.setStatus(SundayCommonConstants.team_status_yjs);
                        teamGroupService.update(teamGroup);
                        //2，修改拼团组人员状态
                        Map<String,Object> param = new HashMap<String,Object>();
                        param.put("groupId",teamGroup.getId());
                        List<SundayTeamGroupMember> teamGroupMembers = teamGroupMemberMapper.select(param);
                        List<Long> orderIds = new ArrayList<>();
                        for(SundayTeamGroupMember teamGroupMember:teamGroupMembers){
                            teamGroupMember.setStatus(SundayCommonConstants.team_status_yjs);
                            teamGroupMemberMapper.update(teamGroupMember);
                            orderIds.add(teamGroupMember.getOrderId());
                        }
                        //3，修改订单状态
                        param.clear();
                        param.put("ids",orderIds);
                      //  logger.info("----------开始修改待拼团订单-----------------");

                        List<SundayOrder> orders = super.select(param);
                        for(SundayOrder o:orders){
                           // logger.info("----------开始修改待拼团订单-----------------");
                            if(o.getStatus()==SundayCommonConstants.ORDER_STATUS_DPT){
                                o.setStatus(SundayCommonConstants.ORDER_STATUS_DFH);
                                super.update(o);
                            }
                        }
                    }

                }

            }
    }

    /**
     * 获取订单
     * @param request
     * @param memberId 用户ID
     * @param status 订单状态。
     * @return
     */
    /**
     * 获取订单
     * @param request
     * @param memberId 用户ID
     * @param status 订单状态
     * @param flag 1，全部订单（不含售后，试用），2我的试用（只有试用订单）3，我的售后（只含售后订单）
     * @return
     */
    public List<SundayOrderDto> getOrders(HttpServletRequest request,Long memberId,Integer status,Integer flag){
        Map<String,Object> param = ParamUtil.packageMysqlPageParam(request,"orderNo");
        param.put("memberId",memberId);
        List<Integer> statuses = new ArrayList<>();
        //判断状态。

        //判断类型
        //  1，全部订单（不含售后，试用）或 2我的试用（只有试用订单）
        if(flag==1||flag==2){
            if(flag==1){
                param.put("type_not_in",Arrays.asList(new Integer[]{SundayCommonConstants.type_shiyong}));
            }
            if(flag==2){
                param.put("type",SundayCommonConstants.type_shiyong);
            }
            if(status==null||status==999){
                statuses.add(SundayCommonConstants.ORDER_STATUS_DFK);
                statuses.add(SundayCommonConstants.ORDER_STATUS_DFH);
                statuses.add(SundayCommonConstants.ORDER_STATUS_PSZ);
                statuses.add(SundayCommonConstants.ORDER_STATUS_YSH);
                statuses.add(SundayCommonConstants.ORDER_STATUS_YPJ);
                statuses.add(SundayCommonConstants.ORDER_STATUS_YQX);
                statuses.add(SundayCommonConstants.ORDER_STATUS_DPT);
            }else{
                statuses.add(status);
            }


        // 2我的试用（只有试用订单）
        }else if(flag==2){

        // 3，我的售后（只含售后订单）
        }else if(flag==3){
            if(status==999){
                statuses.add(SundayCommonConstants.ORDER_STATUS_DTK);
                statuses.add(SundayCommonConstants.ORDER_STATUS_YTK);
                statuses.add(SundayCommonConstants.ORDER_STATUS_DTH);
                statuses.add(SundayCommonConstants.ORDER_STATUS_YTH);
            }else{
                statuses.add(status);
            }

        }
        param.put("statuses",statuses);

        List<SundayOrder> orders = super.select(param);
        List<Long> orderIds = new ArrayList<>();
        for(SundayOrder order:orders){
            orderIds.add(order.getId());
        }
        param.clear();
        param.put("orderIds",orderIds);
        List<SundayOrderProduct> orderProducts =orderProductMapper.select(param);
        return packageBatch(orders,orderProducts);
    }

    /**
     *  获取订单详情
     * @param orderId
     * @param memberId
     * @return
     */
    public SundayOrderDto getDetail(Long orderId,Long memberId){
        SundayOrder order= super.find(orderId);
        Map<String,Object> param = new HashMap<String ,Object>();
        param.put("orderId",order.getId());
        List<SundayOrderProduct> orderProducts =orderProductMapper.select(param);
        List<SundayOrder> orders= new ArrayList<>();
        orders.add(order);
        SundayOrderDto orderDto=packageBatch(orders,orderProducts).get(0);
        //2018年2月4日加载退货地址
     //   if(order.getStatus()==SundayCommonConstants.ORDER_STATUS_DTK||
          //      order.getStatus()==SundayCommonConstants.ORDER_STATUS_DTH){
            orderDto.setAfterSaleAddress(dictionaryService.getDictionaryByKey2("afterSaleAddress").getValue());
      //  }
         return orderDto;
    }

    /**
     * 组装DTO
     * @param orders
     * @param products
     * @return
     */
    public List<SundayOrderDto> packageBatch(List<SundayOrder> orders,List<SundayOrderProduct> products){
        List<SundayOrderDto> orderDtos = new ArrayList<>();
        for(SundayOrder order:orders){
            SundayOrderDto orderDto = new SundayOrderDto(
                    order.getId(), order.getCreateTime(),order.getCreateDate(),
                    order.getOrderNo(), order.getType(),order.getTotalAmount(),order.getPayAmount(),order.getStatus(),
                    order.getMemberIdCard(), order.getMemberRealName(),
                    order.getShopId(), order.getShopName(),
                    order.getReceiveName(), order.getReceiveMobile(), order.getReceiveAddress(),
                    order.getRemark(), order.getInfo(),order.getSendAmount(),
                    order.getAiGouUsedCoin(),order.getAiGouUsedAmount(),order.getCouponAmount(),order.getBalanceUsedAmount(),order.getConchUsedAmount(),order.getSendType());
            //订单中一些额外信息
            orderDto.setSendCompany(order.getSendCompany());
            orderDto.setSendCompanyCode(order.getSendCompanyCode());
            orderDto.setSendCode(order.getSendCode());
            orderDto.setPayTime(order.getPayTime()!=null?TimeUtils.formatToTime(order.getPayTime()):null);
            orderDto.setSendTime(order.getSendTime()!=null?TimeUtils.formatToTime(order.getSendTime()):null);
            orderDto.setReceiveTime(order.getReceiveTime()!=null?TimeUtils.formatToTime(order.getReceiveTime()):null);

            List<SundayOrderProduct> orderProducts = new ArrayList<>();
            Integer totalNum = 0;//订单总件数
            //匹配订单商品
            for(SundayOrderProduct product:products){
                if(LongUtil.isNotZreo(product.getOrderId())&&
                        order.getId().longValue()==product.getOrderId().longValue()){
                    totalNum += product.getNum();
                    orderProducts.add(product);
                }
            }
            orderDto.setTotalNum(totalNum);
            orderDto.setProducts(packageBath(orderProducts));
            orderDtos.add(orderDto);
        }
        return  orderDtos;
    }

    /**
     * 组装订单商品DTo
     * @param products
     * @return
     */
    public List<SundayOrderProductDto> packageBath(List<SundayOrderProduct> products){
        List<SundayOrderProductDto> productDtos = new ArrayList<>();
        for(SundayOrderProduct product:products){
                productDtos.add(new SundayOrderProductDto
                        //传入商品的ID,非订单商品ID
                        (product.getProductId(), product.getCreateTime(),product.getCreateDate(),
                                product.getName(), product.getImage(),
                                product.getNum(), product.getStandard(),
                                product.getPrice(), product.getType()));
            }
            return productDtos;
    }

    /**
     * 确认收货
     * @param memberId
     */
    @Transactional
    public void confirmReceive(Long orderId,Long memberId){
        SundayMember member = memberService.getById(memberId);
        SundayOrder order =checkOrder(orderId,memberId,SundayCommonConstants.ORDER_STATUS_PSZ);
        //更新订单状态 123
        order.setStatus(SundayCommonConstants.ORDER_STATUS_YSH);
        order.setReceiveTime(new Date());
        super.update(order);
        //判断订单类型
        if(order.getType()!=SundayCommonConstants.type_aigou) {
            //奖励一级二级推荐人金额-添加至钱包余额
            Long firstTjId = member.getFirstTjId();//一级推荐人id
            Long secondTjId = member.getSecondTjId();//二级推荐人id
            if (LongUtil.isNotZreo(firstTjId) || LongUtil.isNotZreo(secondTjId)) {
                //需要奖励的金额，2018年2月28日，只查询订单中分销的商品
                Double needRewardAmount = 0.00;
                Map<String, Object> param = new HashMap<String, Object>();
                param.put("orderId", orderId);
                List<SundayOrderProduct> orderProducts = new ArrayList<>();
                List<Long> productIds = new ArrayList<>();
                for (SundayOrderProduct orderProduct : orderProducts) {
                    needRewardAmount += orderProduct.getPrice().doubleValue() * orderProduct.getNum();
                    productIds.add(orderProduct.getProductId());
                }
                //发放分销推荐奖励
                if (needRewardAmount.compareTo(0.00) == 1) {
                    //获取字典维护的奖励比例
                    SystemDictionary firstDictionary = dictionaryService.getDictionaryByKey2("rewardFirstRate");
                    SystemDictionary secondDictionary = dictionaryService.getDictionaryByKey2("rewardSecondRate");
                    BigDecimal firstRate = new BigDecimal(firstDictionary.getValue());//一级推荐奖励比例
                    BigDecimal secondRate = new BigDecimal(secondDictionary.getValue());//二级推荐奖励比例
                    BigDecimal _needRewardAmount = new BigDecimal(needRewardAmount);
                    ///奖励一级推荐人
                    if (LongUtil.isNotZreo(firstTjId)) {
                        BigDecimal firstReward = firstRate.multiply(_needRewardAmount).setScale(2, BigDecimal.ROUND_HALF_UP);
                        walletService.changeWallet(firstTjId, SundayCommonConstants.wallet_record_type_amount_commission, firstReward, order.getOrderNo(), "用户提成:" + needRewardAmount, null);
                    }
                    //奖励二级推荐人
                    if (LongUtil.isNotZreo(secondTjId)) {
                        BigDecimal secondReward = secondRate.multiply(_needRewardAmount).setScale(2, BigDecimal.ROUND_HALF_UP);
                        walletService.changeWallet(secondTjId, SundayCommonConstants.wallet_record_type_amount_commission, secondReward, order.getOrderNo(), "用户提成:" + needRewardAmount, null);
                    }
                    //2018年3月5日，把分销的产品加入到我的店铺中
                    collectionService.saveCollection(order.getMemberId(),SundayCommonConstants.collection_type_fenxiao,productIds);
                }
            }


            //赠送积分和爱购币
            SundayMemberDto memberDto = memberService.packageDtoSingle(member, 0l, true, false);
            //本次赠送的积分
            BigDecimal needSendScore = memberDto.getBuyScore().multiply(order.getTotalAmount());
            //本次赠送的爱购币
            BigDecimal needSendAigou = memberDto.getBuyAgCoin().multiply(order.getTotalAmount());
            //赠送积分
            walletService.changeWallet(memberId, SundayCommonConstants.wallet_record_type_score_shop, needSendScore, order.getOrderNo(), "购买商品赠送积分:" + needSendScore, null);
            //赠送爱购币
            walletService.changeWallet(memberId, SundayCommonConstants.wallet_record_type_coin_shop, needSendAigou, order.getOrderNo(), "购买商品赠送爱购币:" + needSendAigou, null);
        }



    }

    /**
     * 评论订单
     * @param orderId
     * @param productIds
     * @param contents
     * @param scores
     * @param images 图片集合，固定大小=productIds集合大小*3。。每个商品限制最大传入三张，没有图片的使用noImage字符传固定值。
     * @param memberId
     */
    public void  commentOrder(Long orderId,List<Long> productIds,List<String> contents,List<Integer> scores,List<String> images,Long memberId){
        String msg ="";
        //2018-01-29 注释,评论内容可以为空
        if(ListUtil.isNull(productIds)||/*ListUtil.isNull(contents)||*/ListUtil.isNull(scores)){
            msg="评论接口参数有错误(为空)";
        }
        //2018-01-29 注释,评论内容可以为空
        if(/*productIds.size()!=contents.size()||*/productIds.size()!=scores.size()/*||contents.size()!=scores.size()*/){
            msg="评论接口参数有错误（参数不对应）";
        }
        //图片不为空,即上传了图片才进行图片参数校验
        if(ListUtil.isNotNull(images) && productIds.size()*3!=images.size()){
            msg="评论接口参数有错误（图片参数）";
        }
        if(msg!=""){
            throw new ErrorException(msg);
        }
        SundayOrder order=checkOrder(orderId, memberId,SundayCommonConstants.ORDER_STATUS_YSH);
        //更改订单状态
        order.setStatus(SundayCommonConstants.ORDER_STATUS_YPJ);
        super.update(order);
        SundayMember member = memberService.getById(memberId);
        //生成评论
        commentService.generateComment(productIds,
                contents,
                scores,
                images,
                memberId,
                member.getImage(),
                member.getNickName());
        //生成社区动态

        Map<String,Object> param = new HashMap<String,Object>();
        param.put("orderId",orderId);
        List<SundayOrderProduct> orderProducts =orderProductMapper.select(param);
        //1,生成达人试用动态
        if(order.getType()==SundayCommonConstants.type_shiyong){
            dynamicService.saveShiYong(memberId,ListUtil.isNotNull(contents)?contents.get(0):"该用户比较赖，没有评论。",orderProducts, images);
        }else {
          //2，生成本地爱购动态
            dynamicService.saveLocal(memberId,orderProducts,order.getCityId(),order.getCityName(),order.getProvinceId(),order.getProvinceName());
        }

    }

    /**
     * 取消订单
     * @param orderId
     * @param memberId
     */
    public void cancelOrder(Long orderId,Long memberId){
        SundayOrder order=checkOrder(orderId, memberId,SundayCommonConstants.ORDER_STATUS_DFK);
        order.setStatus(SundayCommonConstants.ORDER_STATUS_YQX);

        //需退还的余额-退至钱包余额
        BigDecimal needBackBalance = new BigDecimal(0);
        //需退还爱购币
        BigDecimal needBackAigou = new BigDecimal(0);

        if(order.getAiGouUsedCoin() != null){
            needBackAigou = order.getAiGouUsedCoin();
        }
        if(order.getBalanceUsedAmount() != null){
            needBackBalance = order.getBalanceUsedAmount();
        }
        SundayWallet wallet = walletService.getByMemberId(order.getMemberId());
        //返还支付的金额和爱购币
        wallet.setAigouCoin(wallet.getAigouCoin().add(needBackAigou));
        wallet.setTotalAmount(wallet.getTotalAmount().add(needBackBalance));
        walletService.update(wallet);

        super.update(order);
    }

    /**
     * 申请售后
     * @param orderId
     * @param memberId
     * @param type 6待退款，8待退货
     * @param remark   申请售后原因
     */
    public void afterSale(Long orderId,Long memberId,Integer type,String remark,String afterSendCompany,String afterSendCode){


        SundayOrder order = null;
        //未完待续。
        if(type==SundayCommonConstants.ORDER_STATUS_DTK){
            order =checkOrder(orderId,memberId,SundayCommonConstants.ORDER_STATUS_DFH);
            order.setStatus(SundayCommonConstants.ORDER_STATUS_DTK);
        }else if(type==SundayCommonConstants.ORDER_STATUS_DTH){
            //校验
            if(StringUtils.isBlank(afterSendCompany)){
                throw new ErrorException("您未填写快递公司");
            }
            if(StringUtils.isBlank(afterSendCode)){
                throw new ErrorException("您未填写运单编号");
            }
            order =checkOrder(orderId,memberId,SundayCommonConstants.ORDER_STATUS_PSZ);
            order.setStatus(SundayCommonConstants.ORDER_STATUS_DTH);
            order.setAfterSendCompany(afterSendCompany);
            order.setAfterSendCode(afterSendCode);
        }else{
            throw new ErrorException("售后状态错误");
        }
        order.setAfterRemark(remark);
        super.update(order);
    }



    /**
     * 校验订单状态
     * @param orderId
     * @param memberId
     * @param status
     */
    public SundayOrder checkOrder(Long orderId,Long memberId,Integer status){
            SundayOrder order = super.find(orderId);
            if(order.getMemberId().longValue()!=memberId.longValue()){
                throw new ErrorException(CommonConstants.ERROMSG);
            }
            if(order.getStatus()!=status){
                throw new ErrorException(CommonConstants.ERROMSG);
            }
            return order;
    }

    /**
     * 组装物流查询信息
     * @param orderId
     * @return
     */
    public Map<String,Object> logistics(Long orderId) throws Exception{
        Map<String,Object> result = new HashMap<>();
        String name = "暂无信息";
        String number ="暂无信息";
        List<Map<String,Object>> datas = new ArrayList<>();
        SystemDictionary kd_api_code= dictionaryService.getDictionaryByKey2("kd_api_code");
        SundayOrder order =super.find(orderId);
        String sendCode = order.getSendCode();
        if(StringUtils.isNotEmpty(sendCode)){
            logger.info("--快递单号1-"+sendCode+"--------");
            //后台返回的数据中，有空格，用trim()方法无效，后来发现，表面上看到的空格，unicode为12288，是全角空格，所以要先替换掉再trim()，
            sendCode = sendCode.replaceAll(" ", "");
            sendCode = sendCode.trim();


            logger.info("--快递单号2-"+sendCode+"--------");
            sendCode = URLEncoder.encode(sendCode, "UTF-8");
            String url ="http://wuliu.market.alicloudapi.com/kdi?no="+sendCode;;

            logger.info("--url1-"+url+"--------");
            //处理全角符号
            url = url.replaceAll("%C2%A0", "");
            logger.info("--url2-"+url+"--------");
            Map<String,Object> httpResult= OkHttpUtil.doGetWithHeader(url,kd_api_code.getValue());
            String status =String.valueOf(httpResult.get("status"));
          //  logger.info("---快递--status---"+status);
            if(status.equalsIgnoreCase("0")){
                Map<String,Object> _result =(Map<String,Object>)httpResult.get("result");
                number = String.valueOf(_result.get("number"));
               // logger.info("---快递--number---"+number);
                name= String.valueOf(_result.get("expName"));
               // logger.info("---快递--name---"+name);
                datas=(List<Map<String,Object>>)_result.get("list");
            }
        }
        result.put("name",name);
        result.put("number",number);
        result.put("datas",datas);
        return result;
    }
   /* public Map<String,Object> getKdInfo(String apiCode,String no){
        String host = "http://wuliu.market.alicloudapi.com";
        String path = "/kdi";
        String method = "GET";
        System.out.println("请先替换成自己的AppCode");
        String appcode = apiCode;  // !!!替换填写自己的AppCode 在买家中心查看
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Authorization", "APPCODE " + appcode); //格式为:Authorization:APPCODE 83359fd73fe11248385f570e3c139xxx
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("no", apiCode);// !!! 请求参数
        querys.put("type", no);// !!! 请求参数
        try {
            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
            //System.out.println(response.toString()); //输出头部
            System.out.println(EntityUtils.toString(response.getEntity())); //输出json
        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/
}
